﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WinGetUI
{
    public partial class Form1 : Form
    {
        const int busyWaitTime = 2000;

        public Form1()
        {
            InitializeComponent();
            txtUrl.Text = @"http://www.";
            txtUrl.Focus();
        }

        private void btnExecQuery_Click(object sender, EventArgs e)
        {
            doHttpGet(txtUrl.Text);
        }

        private void doHttpGet(String url)
        {
            if (String.IsNullOrEmpty(url))
            {
                txtHtmlOutput.Text = "";
                return;
            }

            try
            {
                HtmlWeb h = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument d = new HtmlAgilityPack.HtmlDocument();

                WebRequest wr = WebRequest.Create(url);
                wr.Proxy = WebRequest.GetSystemWebProxy();
                wr.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

                d.Load(wr.GetResponse().GetResponseStream());

                if (h.StatusCode != HttpStatusCode.OK) // Oh oh something went wrong
                {
                    MessageBox.Show("An unexpected error occurred ... " + Environment.NewLine + Environment.NewLine + h.StatusCode.ToString());
                }

                foreach (HtmlNode node in d.DocumentNode.Descendants("a"))
                {
                    if (txtHtmlOutput.Text != "")
                        txtHtmlOutput.Text += Environment.NewLine;

                    txtHtmlOutput.Text += node.Attributes["href"].Value;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An unexpected error occurred ... " + Environment.NewLine + Environment.NewLine + e.Message.ToString() + " ... " + Environment.NewLine + Environment.NewLine + e.StackTrace.ToString());
            }
        }
    }
}
